const express = require('express');
const router = express.Router();
const request = require('request');
const pool = require('../pool.js');

router.post('/checkSubscribe', (req, res, next)=>{
	const params = req.body;
	const {openid} = params;
	pool.getConnection(function(error, connection){
		if(error){
			throw error;
		}
		const tokenSql = 'SELECT * FROM userOrder WHERE openid=?';
		const params = [openid];
		connection.query(tokenSql, params, function(err, results, fields){
			if(err){
				throw err;
			}
			connection.release();
			if(results && results.length === 1){
				const base_access_token = results[0].base_access_token;

				let infoURL = `https://api.weixin.qq.com/cgi-bin/user/info`;
				infoURL += `?access_token=${base_access_token}`;
				infoURL += `&openid=${openid}`;
				infoURL += `?&lang=zh_CN`;
				request(infoURL, function(err, response, body){
					if(err){
						throw err;
					}
					console.log(JSON.parse(body));
					res.json({body:JSON.parse(body)});
				});
			}
		});
	});
	
});

module.exports = router;